//
//  SetViewController.m
//  YaoHeAPP
//
//  Created by xyh on 15/12/22.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "SetViewController.h"
#import "Masonry.h"
#import "Controller.h"
#import "YunBaService.h"
#import "AppDelegate.h"
#import "LoginVC.h"
#import "BlackNameVC.h"
#import "SDImageCache.h"
#import "ShowMessageView.h"
#import "UMMobClick/MobClick.h"
#import "WebVC.h"

@interface SetViewController ()<UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate,UIAlertViewDelegate> {
    UITableView *_tableview;
    NSArray *cellName;
    NSArray *files;
}
@end

@implementation SetViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SetViewController"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"SetViewController"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    
     cellName=@[@"黑名单",@"关于我们",@"清除缓存"];
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"设置";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-50);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    //图片
    UIImageView *appimage=[[UIImageView alloc]init];
    [self.view addSubview:appimage];
    [appimage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(navcBar.mas_bottom).offset(35);
        make.width.offset(60);
        make.height.offset(60);
        make.left.offset((self.view.frame.size.width-60)/2);
    }];
    appimage.image=[UIImage imageNamed:@"apploge"];
    

    //版本号
    UILabel *applabel=[[UILabel alloc]init];
    
    //获取版本号信息
    NSDictionary *infoDict=[[NSBundle mainBundle]infoDictionary];
    
    //获取自己版本的信息
    NSString *app_verson=[infoDict objectForKey:@"CFBundleShortVersionString"];
    applabel.text=[NSString stringWithFormat:@"V%@",app_verson];
    applabel.textAlignment=NSTextAlignmentCenter;
    applabel.font=[UIFont systemFontOfSize:15];
    [self.view addSubview:applabel];
    [applabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(appimage.mas_bottom).offset(5);
        make.width.offset(60);
        make.height.offset(30);
        make.left.offset((self.view.frame.size.width-60)/2);
    }];

    //创建表格
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 230, self.view.frame.size.width,150)];
    _tableview.dataSource=self;
    _tableview.delegate=self;
    _tableview.scrollEnabled=NO;
    [self.view addSubview:_tableview];
    

    
    UIButton *button=[[UIButton alloc]init ];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tableview.mas_bottom).offset(40);
        make.width.offset(self.view.frame.size.width);
        make.height.offset(40);
        make.left.offset(0);
    }];
    
    [button addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside ];
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.backgroundColor=[UIColor whiteColor];
    
}

-(void)exit
{
    
     [MobClick event:@"logout"];
    
    // 1.创建UIActionSheet
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"确定要退出吗?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil];
    // 2.显示UIActionSheet
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 判断是否点击类确定按钮
    if (0 == buttonIndex) {
        //退出云吧频道
        
        NSString *usid =[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
        
        
        [YunBaService unsubscribe:usid resultBlock:^(BOOL succ, NSError *error) {
            if (succ) {
                
            } else {
            }
        }];

        
        
        [YunBaService unsubscribe:@"all" resultBlock:^(BOOL succ, NSError *error) {
            if (succ) {
               
            } else {
            }
        }];
        
        //清除本地文件
    
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"状态"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:ISCREATE];
        
        //返回到登录
        LoginVC *loginVC = [[LoginVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        naVC.navigationBarHidden = YES;
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        window.rootViewController = naVC;
        
        // 友盟退出 账号登出时需调用此接口，调用之后不再发送账号相关内容
        [MobClick profileSignOff];
    }
}
-(void)backLogin
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==1) {
        return 1;
    }
    
    return cellName.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"OrderListCell";
    //自定义cell类有图片
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        
        UILabel *namela=[[UILabel alloc]initWithFrame:CGRectMake(45, 12.5, 150, 25)];
        namela.text=cellName[indexPath.row];
        [cell addSubview:namela];
        
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger cellindex=indexPath.row;
    switch (cellindex) {
        case 0:
            
            [MobClick event:@"viewBlacklist"];
            
            //黑名单
            [self blackName];
            break;
        case 1:
            
            [MobClick event:@"aboutUs"];
            
            //意见反馈
            [self feedback];
            break;
        case 2:
            
            [MobClick event:@"cleanHuancun"];
            
            //清除缓存
            [self clearaway];
            break;
        default:
            break;
    }
    
}
//黑名单
-(void)blackName
{
    BlackNameVC*blackName=[[BlackNameVC alloc]init];
    [self.navigationController pushViewController:blackName animated:YES];

}
//意见反馈  关于我们
-(void)feedback
{
//    //拨打电话
//    //进入打电话页面
//    UIWebView *webview = [[UIWebView alloc] init];
//    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:4008850051"]]];
//    [self.view addSubview:webview];

    //[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"tel://4008850051"]];

    
        //获取版本号信息
        NSDictionary *infoDict=[[NSBundle mainBundle]infoDictionary];
    
        //获取自己版本的信息
        NSString *app_verson=[infoDict objectForKey:@"CFBundleShortVersionString"];
    
        WebVC *helpview=[[WebVC alloc]init];
        helpview.titleTxt=@"关于我们";
        NSString*url=[NSString stringWithFormat:@"%@/WEB/mobile/about_us_app.aspx?versionName=v%@",BESTHOST,app_verson];
        helpview.urlString=url;
        [self.navigationController pushViewController:helpview animated:YES];
    

    
    
    
}
//检测新版
-(void)detection
{
    
    //获取版本号信息
    NSDictionary *infoDict=[[NSBundle mainBundle]infoDictionary];

    //获取自己版本的信息
    NSString *app_verson=[infoDict objectForKey:@"CFBundleShortVersionString"];
    NSNumber*number2=[NSNumber numberWithInteger:2];
    NSDictionary*di=@{@"platform":number2};

    [Controller requestWithURL:BANBEN jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            if (![[data.data objectForKey:@"VERSION_NAME"] isEqualToString:app_verson]) {
                 
                 NSInteger  updata=[data.data[@"FORCE_UPDATE"] integerValue];
                 
                 if (updata==0) {
                     //不强制更新
                    UIAlertView * alerter=[[UIAlertView alloc]initWithTitle:@"检测到新版本" message:data.data[@"DESCRIPTION"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新",nil];
                    alerter.tag=2;
                    [alerter show];

                     
                 }else if (updata==1) {
                     //强制更新
                     UIAlertView * alerter=[[UIAlertView alloc]initWithTitle:@"更新应用" message:data.data[@"DESCRIPTION"]  delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新",nil];
                    alerter.tag=3;
                    [alerter show];

                     
                 }

            
                 
            
             }else{
             
                 UIAlertView * alerter=[[UIAlertView alloc]initWithTitle:nil message:@"已经是最新版本" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil ,nil];
                 alerter.tag=4;
                 [alerter show];
                 
             
             }
            
//            "WS_RET_DATA":{
//                "VERSION_CODE":"1",//版本号
//                "DOWNLOAD_URL":"http://www.baidu.com",//下载链接
//                "VERSION_NAME":"1.0",//版本名
//                "DESCRIPTION":"测试测试测试",//更新内容
//                "FORCE_UPDATE":false      //是否强制更新
//            },
//            "WS_RET_MSG":null,
//            "WS_RET_PLAT":"APP",
//            "WS_RET_CODE":0
            
        }
        else
        {
            
        }
    }];
    

    
}


//清除缓存
-(void)clearaway
{
    //获取沙河路径0 1
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    
    files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//    NSString *mess=[NSString stringWithFormat:@"缓存大小为%lu个文件，确定要清除缓存吗？",(unsigned long)[files count]];
//    //初始化AlertView
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                    message:mess
//                                                   delegate:self
//                                          cancelButtonTitle:@"取消"
//                                          otherButtonTitles:@"确定",nil];
//    
//    //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
//    alert.tag = 0;
//    //只读属性，看AlertView是否可见
//    [alert show];

   
    NSString *path;
    for (NSString *p in files) {
        if ([p containsString:@".umeng"] || [p containsString:@"MOBFCacheData"]) {
            continue;
        }
        NSError *error;
        path = [cachPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
    [ShowMessageView showMessage:@"清除成功"];
}

//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    if (alertView.tag==0) {
//        if (buttonIndex==1) {
//            
//            //获取沙河路径0 1
//            NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//            NSString *path;
//            for (NSString *p in files) {
//                NSError *error;
//                path = [cachPath stringByAppendingPathComponent:p];
//                if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
//                    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//                }
//            }
//
//        }
//
//    }
    
    
    
    if(alertView.tag==2){
        
        if (alertView.cancelButtonIndex != buttonIndex) {
            
            //             [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id1071039238"]];
            
            
        }else{
            
        }
        
        
        
    }else if(alertView.tag==3){
        
        if (alertView.cancelButtonIndex != buttonIndex) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id1071039238"]];
            
        }else{
            
        }
        
        
    }
}

@end
